#!/bin/bash

set -e

# 安装脚本
APP_NAME="scene_controller"
INSTALL_DIR="/opt/scene-controller"
CONFIG_DIR="/etc/scene-controller"
LOG_DIR="/var/log/scene-controller"
DATA_DIR="/var/lib/scene-controller"

echo "Installing Scene Strategy Control System..."

# 检查是否以root用户运行
if [ "$(id -u)" -ne 0 ]; then
    echo "Please run as root"
    exit 1
fi

# 创建用户和组
if ! id "scenectl" &>/dev/null; then
    echo "Creating scenectl user..."
    useradd -r -s /bin/false scenectl
fi

# 创建目录
echo "Creating directories..."
mkdir -p $INSTALL_DIR
mkdir -p $CONFIG_DIR
mkdir -p $LOG_DIR
mkdir -p $DATA_DIR

# 复制文件
echo "Copying files..."
cp $APP_NAME $INSTALL_DIR/
cp -r config/* $CONFIG_DIR/
cp scripts/scene-controller.service /etc/systemd/system/

# 设置权限
echo "Setting permissions..."
chown -R scenectl:scenectl $INSTALL_DIR
chown -R scenectl:scenectl $CONFIG_DIR
chown -R scenectl:scenectl $LOG_DIR
chown -R scenectl:scenectl $DATA_DIR
chmod +x $INSTALL_DIR/$APP_NAME

# 创建数据库目录
mkdir -p $DATA_DIR/db
chown scenectl:scenectl $DATA_DIR/db

# 重新加载systemd
echo "Reloading systemd..."
systemctl daemon-reload

# 启用服务
echo "Enabling service..."
systemctl enable scene-controller

echo "Installation completed successfully!"
echo ""
echo "To start the service: systemctl start scene-controller"
echo "To check status: systemctl status scene-controller"
echo "To view logs: journalctl -u scene-controller -f"
